package com.wwdx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * SMTP邮件发送
 * @author liguoliang 
 * @date 2018-04-12
 */
public class Smtp {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * to:收件人
     * from:发件人
     * host:smtp主机
     * username:用户名
     * password:密码
     * subject:邮件主题
     * content:邮件正文
     * port:端口号
     * connectiontimeout:连接超时时间
     * timeout:发送超时时间
     */
    private String to,from,host,username,password,subject,content,formname;
    private Integer port,connectiontimeout,timeout;

    public Smtp(String to, String content) {
        String path = "/properties/constant.properties";
        ConfigReader configReader = new ConfigReader(path);
        this.to = to;
        this.content = content;
        this.port = Integer.parseInt(configReader.get("mail.port"));
        this.connectiontimeout = Integer.parseInt(configReader.get("mail.smtp.connectiontimeout"));
        this.timeout = Integer.parseInt(configReader.get("mail.smtp.timeout"));
        this.from = configReader.get("mail.sender");
        this.host = configReader.get("mail.server");
        this.username = configReader.get("mail.username");
        this.password = configReader.get("mail.password");
        this.subject = configReader.get("mail.subject");
        this.formname = configReader.get("mail.fromname");
    }

    /**
     * 发送邮件
     * @param files 附件
     * @return boolean
     */
    public boolean sendMail(List<File> files) {
        //构造mail session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.timeout", timeout);
        props.put("mail.smtp.connectiontimeout", connectiontimeout);
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.mime.encodefilename", "true");
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        //构造MimeMessage并设定基本的值，创建消息对象
        MimeMessage message = new MimeMessage(session);
        try {
            //发信人
            message.setFrom(new InternetAddress(from, formname, ConstantHolder.Constant.UTF8));
            //收件人地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //邮件主题
            message.setSubject(subject, ConstantHolder.Constant.UTF8);
            //整封邮件的MINE消息体
            Multipart mp = new MimeMultipart();
            //邮件内容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setHeader("Content-Type", "text/html;charset=UTF-8");
            contentPart.setHeader("Content-Transfer-Encoding", "base64");
            contentPart.setContent(content, "text/html;charset=UTF-8");
            mp.addBodyPart(contentPart);

            //添加附件 ( smtp 方式没法使用文件流 )
            for (File file : files) {
                BodyPart attach = new MimeBodyPart();
                attach.setDataHandler(new DataHandler(new FileDataSource(file)));
                attach.setFileName(MimeUtility.encodeWord(file.getName()));
                mp.addBodyPart(attach);
            }

            message.setContent(mp);
            message.setSentDate(new Date());
            //发送邮件
			Transport.send(message);
            return true;
		} catch (MessagingException | UnsupportedEncodingException e) {
            logger.error("错误信息：{}",e.getMessage());
            return false;
        }
    }
}